﻿using Xwltz.Framework.Helper;

namespace Xwltz.Framework.Mvc
{
    public sealed class OperatorProvider<TEntity>
    {
        private OperatorProvider() { }

        private static OperatorProvider<TEntity> _operatorProvider;

        private static readonly object Locker = new object();

        public static OperatorProvider<TEntity> Provider
        {
            get
            {
                if (_operatorProvider == null)
                {
                    lock (Locker)
                    {
                        // 如果类的实例不存在则创建，否则直接返回
                        if (_operatorProvider == null)
                        {
                            _operatorProvider = new OperatorProvider<TEntity>();
                        }
                    }
                }
                return _operatorProvider;
            }
        }

        private const string LoginUserKey = "loginuserkey";
        private readonly string _loginProvider = ConfigHelper.GetValue("LoginProvider");

        public string CurrentUserId;

        public TEntity GetCurrent()
        {
            if (_loginProvider == "Cookie")
            {
                var logininfo = WebHelper.GetCookie(LoginUserKey);
                return logininfo == null ? (TEntity) (object) null : CryptoService.Decode(logininfo).ToObject<TEntity>();
            }
            else
            {
                var logininfo = WebHelper.GetSession(LoginUserKey);
                return logininfo == null ? (TEntity) (object) null : CryptoService.Decode(logininfo).ToObject<TEntity>();
            }
        }

        public void AddCurrent(object account)
        {
            if (_loginProvider == "Cookie")
            {
                WebHelper.SetSession(LoginUserKey, CryptoService.Encode(account.ToJson()), 60);
            }
            else
            {
                WebHelper.SetSession(LoginUserKey, CryptoService.Encode(account.ToJson()));
            }
        }

        public void RemoveCurrent()
        {
            if (_loginProvider == "Cookie")
            {
                WebHelper.RemoveCookie(LoginUserKey.Trim());
            }
            else
            {
                WebHelper.RemoveSession(LoginUserKey.Trim());
            }
        }
    }
}
